package com.baseproject.mvp;


import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

public abstract class MvpBasePresenter<V extends MvpView> implements MvpPresenter<V>{

    public abstract void start();

    public WeakReference<V> mView;

    public CompositeSubscription subscriptions = new CompositeSubscription();

    public void addSubscription(Subscription subscription) {
        subscriptions.add(subscription);
    }

    @Override
    public void attachView(V view) {
        this.mView = new WeakReference<V>(view);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mView != null) {
            this.mView.clear();
            this.mView = null;
        }
        if (!retainInstance) {
            if (subscriptions.hasSubscriptions()) {
                subscriptions.unsubscribe();
            }
        }
    }

    @Override
    public boolean isAttachView() {
        return mView != null && mView.get() != null;
    }

    @Override
    public V getView() {
        return mView == null ? null : mView.get();
    }

    @Override
    public void checkViewAttach() {
        if (!isAttachView()) {
            throw new MvpViewNotAttachedException();
        }
    }

    /**
     * 自定义异常
     */
    public static class MvpViewNotAttachedException extends RuntimeException {
        public MvpViewNotAttachedException() {
            super("请求数据前请先调用 attachView(view) 方法与View建立连接");
        }
    }

    public Map getSimpleQueryParams(String key, String value) {
        Map params = new HashMap<String, String>();
        params.put(key, value);
        return params;
    }

}
